<template>
    <div>
        {{curValue}}
    </div>
</template>

<script>
import MForm from "@/views/modules/components/js/MForm";
import FormBase from "@/views/modules/components/js/FormBase";
export default {
    name: "MChinese",
    mixins:[MForm,FormBase],
    data() {
        return {
            curValue:""
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        toChineseMoney(num) {
            //非数字返回为空
            if(isNaN(num) ){
                return '';
            }
            //将字符串转成数字
            num=Number(num);
            var fraction = [this.i18n('horn','角'),this.i18n('divide','分')];
            var digit = [
                this.i18n('zero','零'), this.i18n('one','壹'), this.i18n('two','贰'),this.i18n('three','叁'),
                this.i18n('wanton','肆'),this.i18n('five','伍'),this.i18n('land','陆'),
                this.i18n('seven','柒'),this.i18n('eight','捌'),this.i18n('nine','玖')];
            var unit = [[this.i18n('first','元'),this.i18n('thousandW','万'),this.i18n('million','亿')],
                ['',this.i18n('pick','拾'),this.i18n('hundred','佰'),this.i18n('thousand','仟')]];
            var head = num < 0? this.i18n('owe','欠'): '';
            num = Math.abs(num);

            var s = '';

            for (var i = 0; i < fraction.length; i++) {
                s += (digit[Math.floor(num * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
            }
            s = s || this.i18n('whole','整');
            num = Math.floor(num);

            for (let i = 0; i < unit[0].length && num > 0; i++) {
                var p = '';
                for (var j = 0; j < unit[1].length && num > 0; j++) {
                    p = digit[num % 10] + unit[1][j] + p;
                    num = Math.floor(num / 10);
                }
                s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
            }

            return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
        }
    },
    watch: {
        data: {
            handler(val) {
                let unit=this.metadata.options.unit || 1;
                if(this.metadata.options.field){
                    let value=val[this.metadata.options.field]
                    this.curValue=this.toChineseMoney(value*unit);
                }
            },
            deep: true,
            immediate: true
        },
    },
}
</script>
